package com.cheng.jvm;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author yangcheng
 * @version 1.0
 * @date 2021-06-26 22:11
 * @description
 */
public class MyClassLoader extends ClassLoader {

    private String classPath;

    public MyClassLoader(String classPath) {
        this.classPath = classPath;
    }

    /**
     * load方法调用是会调用findClass方法
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] data = loadByte(name);
            return defineClass(name, data, 0, data.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ClassNotFoundException();
        }

    }

    /**
     * 获取.class的字节流
     *
     * @param name
     * @return
     * @throws Exception
     */
    private byte[] loadByte(String name) throws Exception {
        name = name.replaceAll("\\.", "/");
        FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
        int len = fis.available();
        byte[] data = new byte[len];
        fis.read(data);
        fis.close();

        return data;
    }

    //加密方法(同时可以解密)
    private static void cypher(InputStream ips , OutputStream ops)throws Exception{
        int b = -1;
        while((b=ips.read())!=-1){
            //在写入之前进行异或运算
            ops.write(255-b);
        }
    }
}
